package com.hyw.trace.configuration.meta.redis;

import java.util.Objects;

import org.springframework.data.redis.core.RedisTemplate;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.hyw.trace.configuration.meta.IEventStorage;
import com.hyw.trace.configuration.meta.TraceEvent;
import com.hyw.trace.configuration.meta.redis.queue.ICacheQueue;
import com.hyw.trace.configuration.meta.redis.queue.RedisQueueBuilder;
import com.hyw.trace.configuration.meta.redis.queue.RedisQueueBuilder.QueueType;

public class RedisEventStorage implements IEventStorage<TraceEvent> {

  private final ICacheQueue<String> simpleQueue;

  private final ObjectMapper obj = new ObjectMapper();

  public RedisEventStorage(RedisTemplate<String, String> redisTemplate, String topic) {
    super();
    Objects.requireNonNull(redisTemplate);
    Objects.requireNonNull(topic);
    this.simpleQueue = RedisQueueBuilder.create(topic, redisTemplate).setQueueType(QueueType.Simple).build();
  }

  @Override
  public void storage(TraceEvent data) {
    try {
      this.simpleQueue.add(obj.writeValueAsString(data));
    } catch (JsonProcessingException e) {
      throw new RuntimeException(e);
    }
  }

}
